import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { SettingDrawer } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { services } from '@/services';
import defaultSettings from '../config/defaultSettings';
import { LocalStorage } from '@/utils';
import type { Nullable_Array, User } from './types';

const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

interface InitialState {
  settings?: Partial<LayoutSettings>;
  user?: User;
  loading?: boolean;
  login: boolean;
}
export async function getInitialState(): Promise<InitialState> {
  const state: InitialState = {
    settings: defaultSettings,
    login: false,
  };
  const [login, _user] = LocalStorage.get_batch<Nullable_Array<[boolean, User]>>(['login', 'user']);
  if (login) {
    state.login = true;
    const user = await services.global.fetchUserInfo().catch(() => undefined);
    if (user) state.user = user;
  }
  return state;
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.user?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.user && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                  login: preInitialState?.login ?? false,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
